<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no">
    <meta http-equiv="X-UA-Compatible" content="ie=edge,chrome=1">
    <meta name="referrer" content="never">
    <title>滚动跟随</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
        ul {
            list-style: none;
        }

        .container {
            width: 1200px;
            height: 3000px;
            margin: 50px auto;
            background-color: rgba(255, 255, 0, .5);
        }

        .advance {
            position: absolute;
            top: 600px;
            right: 70px;
            width: 80px;
            height: 120px;
            background-color: #f00;
        }
    </style>
</head>
<body>
    <div class="container"></div>
    <div class="advance">这是一条小广告</div>

    <script type="text/javascript">
        var adv = document.querySelector(".advance");
        // 广告距离页面的原始高度
        var originTop = adv.offsetTop;

        window.onscroll = function (){
            // 获取卷入高度
            var sct = window.pageYOffset;

            // adv.style.top = originTop + sct + "px";
            move(adv, originTop + sct);
        }


        function move(ele, end){
            if(ele.timer){
                clearInterval(ele.timer);
            }
            ele.timer = setInterval(function (){
                // 获取起点
                var start = ele.offsetTop;
                // 设置步长
                var step = (end - start)/10;
                // 修正步长 
                if(Math.abs(step) < 1){
                    step = step > 0 ? 1 : Math.floor(step);
                }

                // 运动
                ele.style.top = start + step + "px";

                // 判断结束
                if(start + step == end){
                    clearInterval(ele.timer);
                    console.log("end ...");
                    ele.timer = null;
                }
            }, 1000/60)
        }
    </script>
</body>
</html>